# 导入sqlite的驱动
import sqlite3
from sqlite3 import Connection, Cursor

# 定义一个数据库连接类
    # 初始化
class DatabaseDriver:
        # 初始化
    def __init__(self, username: str = '', password: str = ''):
        self.connection = False
        if username == '' and password == '':
            self.conn: Connection = sqlite3.connect('C:/Users/17815/PycharmProjects/vending-machine/db/books.db')
            self.connection: bool = True

        # 关闭连接
    def close(self):
        self.conn.close()
        self.connection = False

    def update(self, sql: str, log: bool = False):
        if self.connection:
            cursor = self.conn.cursor()
            if log:
                # 如果打开日志功能，则输出当前的sql语句
                print('sql execute: {}'.format(sql))
            c = cursor.execute(sql)
            if log:
                print("sql update count: {}".format(self.conn.total_changes))
            self.conn.commit()
            return self.conn.total_changes
        else:
            raise Exception('数据库已经关闭')

    def insert(self, sql: str, log: bool = False):
        return self.update(sql, bool)

    def delete(self, sql: str, log: bool = False):
        if self.connection:
            cursor = self.conn.cursor()
            if log:
                # 如果打开日志功能，则输出当前的sql语句
                print('sql execute: {}'.format(sql))
            c = cursor.execute(sql)
            if log:
                print("sql delete count: {}".format(self.conn.total_changes))
            self.conn.commit()
            return self.conn.total_changes
        else:
            raise Exception('数据库已经关闭')

    def select_one(self, sql: str, log: bool = False):
        if self.connection:
            cursor = self.conn.cursor()
            if log:
                print('sql execute: {}'.format(sql))
                c = cursor.execute(sql)
                self.conn.commit()
                data = c.fetchone()
                if log:
                    print('sql execute result: {}'.format(data))
                    return data
            else:
                raise Exception('数据库已经关闭')

    def select_all(self, sql: str, log: bool = False):
        if self.connection:
            cursor = self.conn.cursor()
            if log:
                print('sql execute: {}'.format(sql))
                c = cursor.execute(sql)
                self.conn.commit()
                data = c.fetchall()
                if log:
                    print('sql execute result lengths: {}'.format(len(data)))
                    for index, d in enumerate(data):
                        print("sql execute result{}: {}".format(index + 1, d))
                return data
            else:
                raise Exception('数据库已经关闭')

if __name__ == '__main__':
    db = DatabaseDriver()
    db.select_all(sql='select * from user where 1 = {}'.format(1), log=True)

